package com.shgsh.server.service;


import com.alibaba.fastjson.JSON;
import com.shgsh.server.model.IMSignal;
import com.shgsh.server.model.IMUser;
import com.shgsh.server.repository.CURDRepository;
import com.shgsh.server.utils.SSDBTable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by pcc on 2015/8/13.
 */

public class IMUserService {
    Logger logger = LoggerFactory.getLogger(IMUserService.class);

    CURDRepository curdRepository = new CURDRepository();

    /**
     * 用户数据表
     * hashmap  Map              key       value
     *          user_data_table  用户ID  Json(User)
     */

    /**
     * 根据用户id获取用户个人信息
     * @param userId
     * @return
     */
    public IMUser getUser(String userId) {
        ArrayList<byte[]> hgetParams = new ArrayList<>();
        hgetParams.add(SSDBTable.USER_DATA_TABLE.getBytes());
        hgetParams.add(userId.getBytes());
        String result = curdRepository.hget(hgetParams);
        logger.debug("result = " + result);
        if (!StringUtils.isEmpty(result)) {
            logger.debug("get userInfo successfully form SSDB where userid is " + userId);
            return JSON.parseObject(result, IMUser.class);
        } else
            logger.debug("fail to get userInfo form SSDB where userid is " + userId);
        return null;
    }

    /**
     * 获取所有在线的用户
     * @return
     */
    public List<IMUser> getIMUsers(){
        List<IMUser> activeUsers = new ArrayList();
        Map<String,String> result = curdRepository.hgetAll(SSDBTable.USER_DATA_TABLE);
        Iterator<String> it = result.keySet().iterator();
        if(it != null){
            IMUser user = null;
            while(it.hasNext()){
                String userStr = it.next();
                if(!StringUtils.isEmpty(userStr)){
                    user = (IMUser)JSON.parseObject(userStr,IMUser.class);
                    if(user.getActiveState().equals("0")){
                        activeUsers.add(user);
                    }
                }
            }
            logger.debug("get users who are active !");
        }
        return activeUsers;
    }

    /**
     * 获取所有用户
     * @return
     */
    public List<IMUser> getAllUsers(){

        List<IMUser> users = new ArrayList();
        Map<String,String> result = curdRepository.hgetAll(SSDBTable.USER_DATA_TABLE);
        Iterator<String> it = result.keySet().iterator();
        if(it != null){
            IMUser user = null;
            while(it.hasNext()){
                String userStr = it.next();
                if(!StringUtils.isEmpty(userStr)){
                    user = (IMUser)JSON.parseObject(userStr,IMUser.class);
                    users.add(user);
                }
            }
            logger.debug("get all users !");
        }
        return users;
    }

    /**
     * 判断用户是否进入世界模块
     * @param userId
     * @return
     */
    public boolean havenLogin(String userId) {
        ArrayList<byte[]> hgetParams = new ArrayList<>();
        hgetParams.add(SSDBTable.USER_SPECIFIC_TABLE.getBytes());
        hgetParams.add(userId.getBytes());
        String result = curdRepository.hget(hgetParams);
        logger.debug("r --- " + result);
        return !StringUtils.isEmpty(result);
    }

    /**
     * 获取用户标识
     * @param userId
     * @return
     */
    public IMSignal getIMSignal(String userId){
        logger.debug(userId + " get signal ");
        ArrayList<byte[]> hgetParams = new ArrayList<>();
        hgetParams.add(SSDBTable.USER_SPECIFIC_TABLE.getBytes());
        hgetParams.add(userId.getBytes());
        String result = curdRepository.hget(hgetParams);
        IMSignal signal = null;
        if(!StringUtils.isEmpty(result)){
            signal = JSON.parseObject(result,IMSignal.class);
            return signal;
        }
        return null;
    }

    /**
     * 保存用户标识表
     * @param imSignal
     */
    public void saveIMSignal(IMSignal imSignal){
        ArrayList<byte[]> hgetParams = new ArrayList<>();
        hgetParams.add(SSDBTable.USER_SPECIFIC_TABLE.getBytes());
        hgetParams.add(imSignal.getUserId().getBytes());
        hgetParams.add(imSignal.toJson().getBytes());
        curdRepository.hset(hgetParams);
    }
    /**
     * 判断是否存在该用户
     * @param username
     * @return
     */
    public IMUser isUser(String username){
        logger.debug("check login ： username = " + username);
        ArrayList<byte[]> hgetParams = new ArrayList<>();
        hgetParams.add(SSDBTable.USER_DATA_TABLE.getBytes());
        hgetParams.add(username.getBytes());
        String result = curdRepository.hget(hgetParams);
        logger.debug("result = " + result);
        if(StringUtils.isEmpty(result)) {
            return JSON.parseObject(result, IMUser.class);
        }else{
            return null;
        }
    }

    public void save(IMUser user){
        ArrayList<byte[]> hsetParams = new ArrayList<>();
        hsetParams.add(SSDBTable.USER_DATA_TABLE.getBytes());
        hsetParams.add(user.getId().getBytes());
        hsetParams.add(user.toJson().getBytes());
        curdRepository.hset(hsetParams);
        logger.debug("save user : " + user.getUsername());
    }

    /**
     * 删除指定用户id的用户标识记录，即进入世界树
     * @param userId
     */
    public void deleteSignalForUser(String userId){
        ArrayList<byte[]> hdelParams = new ArrayList<>();
        hdelParams.add(SSDBTable.USER_SPECIFIC_TABLE.getBytes());
        hdelParams.add(userId.getBytes());
        curdRepository.hdel(hdelParams);
    }

    /*public void saveUserSpecificData(String userId,String ipAndPort){
        ArrayList<byte[]> hsetParams = new ArrayList<>();
        hsetParams.add(SSDBTable.USER_SPECIFIC_TABLE.getBytes());
        hsetParams.add(userId.getBytes());
        hsetParams.add(ipAndPort.getBytes());
        curdRepository.hset(hsetParams);
        log.info("save user specific data . user id is : " + userId);
    }*/

    /*public boolean login(String username,String password){
        try {
            IMUser user = isUser(username);
            if (user != null) {
                String rePassword = SecurityUtil.generatePassword(username,password);
                if(user.getPassword().equals(rePassword)){
                    System.out.println("login success !");
                    return true;
                }
            }
        } catch (Exception e) {
            log.info("Unknown User!");
        }
        return false;
}*/

}
